package com.zzh.ScheduledThreadExecutor;


import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 *@ClassName SingleThreadExecutor
 *@date 2021/2/8 11:34
 *@Version 1.0
 *@Description //
 */
@Slf4j
public class ScheduledThreadExecutorDemo {

    public static void main(String[] args) {
        ScheduledThreadPoolExecutor scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1);
        ScheduledFuture<Integer> future = scheduledThreadPoolExecutor.schedule(() -> {
            System.out.println("我要延迟5s执行");
            return 1;
        }, 5000, TimeUnit.MICROSECONDS);

        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        //并不能解决我的任务时长超过周期时长的情况，只是掩盖了
        scheduledThreadPoolExecutor.scheduleAtFixedRate(()->{
            log.info("sen heart beat");
            long statrtime = System.currentTimeMillis(),nowtime= statrtime;
            while ((nowtime - statrtime) > 5000) {
                nowtime = System.currentTimeMillis();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info("task over");
                //如果抛出异常这这个任务就直接丢了
                throw new RuntimeException("stop working");
            }
        },1000,2000,TimeUnit.MICROSECONDS);

        //可以解决我任务时长超过周期时长的情况
//        scheduledThreadPoolExecutor.scheduleWithFixedDelay(()->{
//            log.info("sen heart beat");
//            long statrtime = System.currentTimeMillis(),nowtime= statrtime;
//            while ((nowtime - statrtime) > 5000) {
//                nowtime = System.currentTimeMillis();
//                try {
//                    Thread.sleep(100);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                log.info("task over");
//                throw new RuntimeException("stop working");
//            }
//        },1000,2000,TimeUnit.MICROSECONDS);


        

    }



}
